//
//  WGDataService.m
//  WorkGo
//
//  Created by 李树志 on 2017/10/1.
//  Copyright © 2017年 李树志. All rights reserved.
//

#import "WGDataService.h"
#import "WGApiService.h"

@interface WGDataService ()
{
    int _month;
    int _day;
    int _sum;
    NSInteger _year;
    NSArray *_leapYear;
    NSArray *_commonYear;
    BOOL _isLeapYear;
}
@end

@implementation WGDataService

- (instancetype)init
{
    self = [super init];
    if (self) {
        _month = 1;
        _day = 1;
        _sum = 0;
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDateComponents *components = [calendar components:NSCalendarUnitYear fromDate:[NSDate date]];
        _year = components.year;
        _leapYear = @[@31,@29,@31,@30,@31,@30,@31,@31,@30,@31,@30,@31];
        _commonYear = @[@31,@28,@31,@30,@31,@30,@31,@31,@30,@31,@30,@31];
        _isLeapYear = (_year % 4 == 0 && _year % 100 != 0) || _year % 400 == 0;
    }
    return self;
}

+ (instancetype)sharedService {
    static WGDataService *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[WGDataService alloc] init];
    });
    return _instance;
}

- (void)refreshDataProgress:(void (^)(float))progressHandler
                 completion:(void (^)(NSError *))completionHandler
{
    WGApiService *service = [WGApiService sharedService];
    __weak typeof(self) theApplication = self;
    int days = _isLeapYear ? [_leapYear[_month - 1] intValue] : [_commonYear[_month - 1] intValue];
    service.currentDate = [NSString stringWithFormat:@"%zd-%02d-%02d",_year, _month, _day];
    [service sendCalendarRequest:^(WGDay *day, NSError *error) {
        _sum++;
        if (progressHandler) {
            float total = _isLeapYear ? 366.0 : 365.0;
            float pro = _sum / total;
            progressHandler(pro);
        }
        if (day) {
            if (_day < days) {
                _day++;
            } else {
                _day = 1;
                _month++;
            }
            if (_day < 32 && _month < 13) {
                [theApplication refreshDataProgress:progressHandler completion:completionHandler];
            } else {
                if (completionHandler) {
                    completionHandler(nil);
                }
            }
        } else {
            NSLog(@"Request Error: %@", error);
            if (completionHandler) {
                completionHandler(error);
            }
        }
    }];
}

@end
